package com.cuhk.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cuhk.common.constant.ProductConstant;
import com.cuhk.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.cuhk.gulimall.product.dao.AttrGroupDao;
import com.cuhk.gulimall.product.dao.CategoryDao;
import com.cuhk.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.cuhk.gulimall.product.entity.AttrGroupEntity;
import com.cuhk.gulimall.product.entity.CategoryEntity;
import com.cuhk.gulimall.product.service.CategoryService;
import com.cuhk.gulimall.product.vo.AttrRespVo;
import com.cuhk.gulimall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cuhk.common.utils.PageUtils;
import com.cuhk.common.utils.Query;

import com.cuhk.gulimall.product.dao.AttrDao;
import com.cuhk.gulimall.product.entity.AttrEntity;
import com.cuhk.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attrVO) {
        // 保存属性信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVO, attrEntity);
        this.save(attrEntity);

        // 如果指定了关联关系,则保存关联关系
        if(attrVO.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attrVO.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrVO.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attrVO) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVO, attrEntity);

        this.updateById(attrEntity);

        if(attrVO.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 修改分组信息关联
            int count = attrAttrgroupRelationDao.selectCount(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVO.getAttrId())
            );
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrVO.getAttrGroupId());
            if(count > 0) {
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVO.getAttrId())
                );
            }
            else {
                attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }

    }

    @Override
    public PageUtils queryAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type",
                "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():
                        ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> res = records.stream().map((item) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(item, attrRespVo);

            // 补充分类名称到VO实体
            Long cid = item.getCatelogId();
            CategoryEntity categoryEntity = categoryDao.selectById(cid);
            if(categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            // 补充属性所在分组名称到VO实体
            if("base".equalsIgnoreCase("attrType")) {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", item.getAttrId())
                );
                if(attrAttrgroupRelationEntity != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                    attrRespVo.setAttrGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(res);
        return pageUtils;
    }

    /**
     * 开启缓存
     * @param attrId
     * @return
     */
    @Cacheable(value = {"attr_info"}, key = "#root.args[0]", sync = true)
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        // 先查到AttrEntity
        AttrEntity attrEntity = attrDao.selectById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrRespVo);

        // 补充分类信息
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        if(categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
            // 补充catelogPath
            Long[] catelogPath = categoryService.findCateLogPath(attrEntity.getCatelogId());
            attrRespVo.setCatelogPath(catelogPath);
        }

        // 补充分组信息
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId)
            );
            if(relationEntity != null) {
                attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if(attrGroupEntity != null) {
                    attrRespVo.setAttrGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        return attrRespVo;
    }

    /**
     * 根据分组id查找关联的所有基本属性
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_group_id", attrGroupId);
        List<AttrAttrgroupRelationEntity> list = attrAttrgroupRelationDao.selectList(wrapper);
        if(list == null || list.isEmpty()) {
            return null;
        }
        List<Long> attrIds = list.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    /**
     * 结果集约束：
     * 1. 属性的类别，必须和当前分组所属的类别保持一致 -> catelogId
     * 2. 属性不能已经被关联至其他分组
     * @param attrGroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils getRelationNoAttr(Long attrGroupId, Map<String, Object> params) {
        // 获取分组所属分类
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        // 当前分组下的attr_id不能有
        List<Long> idList = getList(attrGroupId);

        // 和当前分组类别相同的分组下的attr_id不能有
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("catelog_id", catelogId).ne("attr_group_id", attrGroupId);
        List<AttrGroupEntity> groups = attrGroupDao.selectList(wrapper);
        List<Long> idList2 = new ArrayList<>();
        for(AttrGroupEntity group : groups) {
            Long groupId = group.getAttrGroupId();
            idList2.addAll(getList(groupId));
        }

        idList.addAll(idList2);

        QueryWrapper<AttrEntity> wrapper2 = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isBlank(key)) {
            wrapper2.eq("attr_id", key).or().like("attr_name", key);
        }
        wrapper2.eq("catelog_id", catelogId);
        if(!idList.isEmpty()) {
            wrapper2.notIn("attr_id", idList);
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper2);
        return new PageUtils(page);

    }

    private List<Long> getList(Long attrGroupId) {
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("attr_group_id", attrGroupId);
        List<AttrAttrgroupRelationEntity> relations = attrAttrgroupRelationDao.selectList(wrapper1);
        if(relations == null || relations.isEmpty()) {
            return new ArrayList<>();
        }
        List<Long> ids = relations.stream().map((relation) -> {
            return relation.getAttrId();
        }).collect(Collectors.toList());
        return ids;
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> targetAttrIds) {
        return attrDao.selectSearchAttrIds(targetAttrIds);
    }

}